//
//  SXSingletonClass.m
//  SXDataManager_Example
//
//  Created by wangshuixin on 2019/1/10.
//  Copyright © 2019 wangshuixin. All rights reserved.
//

#import "SXSingletonClass.h"
#import <objc/runtime.h>

@implementation SXSingletonClass
SXSingletonM(SXSingletonClass)
- (instancetype)init {
    if (self = [super init]) {
        NSLog(@"单例创建！");
        
    }
    return self;
}

- (instancetype)initWithDict:(NSDictionary *)dict {
    if (self = [super init]) {
        [self setValuesForKeysWithDictionary:dict];
        NSLog(@"类的所有属性：%@", [SXSingletonClass getAllProperty:self]);
    }
    return self;
}

/**
 字典转模型
 原理：所有继承于NSObject的类，都会继承NSKeyValueCoding协议，字典转模型时，需要self对象调用setValuesForKeysWithDictionary方法，底层基于runtime获取到类所有的属性，再通过setValue: forKey:来将字典中的keyValue转换为模型对应的值；
 @param dict 传入值
 @return 模型
 */
+ (instancetype)modelWithDictionary:(NSDictionary *)dict {
    return [[self alloc] initWithDict:dict];
}

//获得所有属性
+ (NSArray *)getAllProperty:(id)object{
    NSMutableArray *array = [NSMutableArray array];
    
    unsigned int count;
    objc_property_t *propertys = class_copyPropertyList([object class], &count);
    for (int i = 0; i < count; i++) {
        objc_property_t property = propertys[i];
        const char *nameChar = property_getName(property);
        NSString *nameStr = [NSString stringWithCString:nameChar encoding:NSUTF8StringEncoding];
        [array addObject:nameStr];
    }
    return [array copy];
}

@end
